package cn.wowjoy.pda.android_pharmacy.ui.activity.door.take;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import cn.wowjoy.pda.android_pharmacy.R;
import cn.wowjoy.pda.android_pharmacy.common.core.BaseActivity;
import cn.wowjoy.pda.android_pharmacy.common.utils.Contants;
import cn.wowjoy.pda.android_pharmacy.common.utils.NetWorkUtils;
import cn.wowjoy.pda.android_pharmacy.common.utils.PreferenceManager;
import cn.wowjoy.pda.android_pharmacy.common.widget.CreateDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MDialog;
import cn.wowjoy.pda.android_pharmacy.common.widget.MyToast;
import cn.wowjoy.pda.android_pharmacy.databinding.ActivityDoorTakeProgressBinding;
import cn.wowjoy.pda.android_pharmacy.model.xmlEntity.doorPatientInfo.DoorPatientInfoBeen;
import cn.wowjoy.pda.android_pharmacy.mvvm.presenter.DoorTakeProgressPresenter;
import cn.wowjoy.pda.android_pharmacy.mvvm.vm.DoorTakeProgressViewModel;

/**
 * 存在的问题：
 * 1.各个界面 使用back键退出
 * 2.最终结果更新失败，或者是多人同时操作同一个订单
 * 3.进度条的更新问题
 */
public class DoorTakeProgressActivity extends BaseActivity<ActivityDoorTakeProgressBinding, DoorTakeProgressViewModel, DoorTakeProgressPresenter> implements DoorTakeProgressPresenter.OnScanResult, DoorTakeProgressPresenter.OnSubmitResult {
    private MDialog failSubmit;
    private MDialog mMDialog;
    private float countAlready = 0;
    private DoorPatientInfoBeen remove;
    //当次药单 种类总数量
    private  float TOTAL_NUM = Integer.parseInt(PreferenceManager.getInstance().getDoorMedicineProgressTotal());
    //设置缓存柜是否成功
    private boolean isSetCache = false;
    //是否取完药
    private boolean isGetAll = false;
    //收到的缓存柜 位置
//    private String cachePlace;

    //PDA扫码广播
    private ScanReceiverDoorTake mScanReceiver;
    private IntentFilter intentFilter;

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViweModel(viewModel);
        binding.setPresenter(presenter);
        if(presenter.type == 1){
            binding.medicineIdScanGet.setVisibility(View.GONE);
            binding.chufanghaoScanGet.setVisibility(View.GONE);
        }else{
            binding.medicineIdScanGet.setVisibility(View.VISIBLE);
            binding.chufanghaoScanGet.setVisibility(View.VISIBLE);
            binding.medicineIdScanGet.setText(presenter.DJJLID);
        }
        binding.scanGetTitle.titleTextTv.setText("扫码取药");
        binding.scanGetTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.llScanGetStart.setVisibility(View.VISIBLE);
        binding.llScanGetEnd.setVisibility(View.GONE);
        presenter.registeOnScanResultListener(this);
        presenter.registeOnSubmitResultListener(this);
        //跳过 删除当前显示在页面上的药
        binding.scanGetTitle.titleMenuConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculate();
              updateFirstUI();
            }
        });
        binding.scanGetTitle.titleBackLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (viewModel.mMoveBaens.size() != 0) {
                    viewModel.mMoveBaens.add(0,remove);
                }
                if (TOTAL_NUM - countAlready == 1) {
                    viewModel.mMoveBaens.add(0,remove);
                }
                intent.putExtra("currently", viewModel.mMoveBaens);
                setResult(Contants.REQUEST_BACK_CODE, intent);
                finish();
            }
        });
        binding.scanGetTitle.titleBackTv.setText("取药单详情");
        binding.btDoorTakeProgressSureSuccess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO:整个单子完成，跳转到Index     还要判断是否是2人同时操作同一个订单 先后完成？？
//                if(binding.tvScanGetScan.getText().toString().trim().equals("") ||
//                        !binding.tvScanGetScan.getText().toString().trim().equals("请重新扫码，设置缓存柜")){
//                    presenter.update("1", PreferenceManager.getInstance().getLUserId());
//                }
                if(NetWorkUtils.isWifi(DoorTakeProgressActivity.this)){
                    if(presenter.type == 1){
                        //TODO:三条单子都要进行跟新
//                        presenter.update(presenter.DJJLID,"1", PreferenceManager.getInstance().getLUserId());
                    }else{
                        presenter.update(presenter.DJJLID,"1", PreferenceManager.getInstance().getLUserId());
                    }
                }else{
                    CreateDialog.failDialog3(DoorTakeProgressActivity.this,"错误","当前网络不可用，请检查你的网络设置");
                }
            }
        });

        //TODO:进度条更新   分子什么时候加一
        ifBack();
        updateFirstUI();
        //TODO:PDA扫码广播的接收跳转
        mScanReceiver = new ScanReceiverDoorTake();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Contants.WOW_NEW_ADD);

    }
    public void calculate(){
        //进度+1 ，界面展现集合中的第一个
        if (countAlready < TOTAL_NUM) {
            countAlready++;
        }

        if (countAlready == TOTAL_NUM) {
            //扫码完成
            binding.scanGetTitle.titleTextTv.setText("放入缓存柜");
            binding.llScanGetStart.setVisibility(View.GONE);
            binding.llScanGetEnd.setVisibility(View.VISIBLE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.btDoorTakeProgressSureSuccess.setVisibility(View.VISIBLE);
            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
            binding.tvProgressScanGet.setText((int)countAlready + "/" + (int)TOTAL_NUM);
            binding.progressScanGet.setProgress((int)((countAlready /TOTAL_NUM)*100));
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Contants.REQUEST_CODE:
                switch (resultCode) {
                    case Contants.RESULT_SUCCESS_CODE:
                        calculate();
                        updateFirstUI();
                        break;
                    case Contants.RESULT_FAIL_CODE:
                        //back键 界面不做更新

                        break;
                }
                break;
        }
    }

    private void ifBack() {
        //说明是0/12 Back回去的
//        if(viewModel.FirstTotal.size() == TOTAL_NUM){
//            Log.e("Back回去的", "updateFirstUI: "+  TOTAL_NUM);
//            binding.tvProgressScanGet.setText(countAlready+"/"+ TOTAL_NUM);
//        }
        //说明是中途取到2/12 回去的
        if (viewModel.FirstTotal.size() < TOTAL_NUM) {
            countAlready = TOTAL_NUM - viewModel.FirstTotal.size();
//            Log.e("中途取到2/12", "updateFirstUI: " + TOTAL_NUM + "  countAlready:" + countAlready);
//            binding.tvProgressScanGet.setText(countAlready+"/"+ TOTAL_NUM);
        }
    }

    //TODO:界面药品信息的更新   库位和处方号的更新？？
    private void updateFirstUI() {
        binding.tvProgressScanGet.setText((int)countAlready + "/" + (int) TOTAL_NUM);
        if (viewModel.mMoveBaens.size() > 0) {
            remove = viewModel.remove();
//            Log.e("remove", "updateFirstUI: "+remove.toString() );

            if( null != remove.getKFWZMC() && remove.getKFWZMC().length()>6){
                binding.locatorScanGet.setText(remove.getKFWZMC().substring(0,7));  //库位
            }else{
                binding.locatorScanGet.setText(""+remove.getKFWZMC());  //库位
            }
            if(null == remove.getSFLCPB() || "".equals(remove.getSFLCPB())){
                binding.scanGetTitle.titleMenuConfirm.setVisibility(View.GONE);
                binding.cold.setVisibility(View.GONE);
            }else if("1".equals(remove.getSFLCPB())){
                    binding.scanGetTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
                    binding.cold.setVisibility(View.VISIBLE);
            }else if("0".equals(remove.getSFLCPB())){
                binding.scanGetTitle.titleMenuConfirm.setVisibility(View.GONE);
                binding.cold.setVisibility(View.GONE);
            }


            if(null != remove.getSFGWPB() && !"".equals(remove.getSFGWPB())){
                if(Integer.parseInt(remove.getSFGWPB()) == 1){
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.red));
                }else {
                    binding.medicineNameScanGet.setTextColor(getResources().getColor(R.color.text_undanger));
                }
            }
            binding.medicineNameScanGet.setText(remove.getZZYPMC()+"  "+remove.getZZYPGG());
            //数量
            binding.numScanGet.setText(remove.getCFYPSL()+" "+remove.getYPBZDW());
            //产地
            binding.placeScanGet.setText(remove.getYPCDMC());
            binding.progressScanGet.setProgress((int)((countAlready /TOTAL_NUM)*100));
        }
        if (countAlready == TOTAL_NUM) {
            //8/8 BACK回去的
            binding.scanGetTitle.titleTextTv.setText("放入缓存柜");
            binding.llScanGetStart.setVisibility(View.GONE);
            binding.llScanGetEnd.setVisibility(View.VISIBLE);
            binding.rlVoice.setVisibility(View.VISIBLE);
            binding.btDoorTakeProgressSureSuccess.setVisibility(View.VISIBLE);
            binding.scanGetTitle.titleBackLl.setVisibility(View.GONE);
            binding.progressScanGet.setProgress(100);
        }
    }

    @Override
    protected int getLayoutId(  ) {
        return R.layout.activity_door_take_progress;
    }

    @Override
    protected Class<DoorTakeProgressPresenter> getPresenterClass() {
        return DoorTakeProgressPresenter.class;
    }

    @Override
    protected Class<DoorTakeProgressViewModel> getViewModelClass() {
        return DoorTakeProgressViewModel.class;
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mScanReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CreateDialog.dismiss(DoorTakeProgressActivity.this);
        if(null != mMDialog){
            mMDialog.cancel();
        }
        if(null != failSubmit){
            failSubmit.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        //药单未完成  BACK键返回  每次要把当前展示的加到集合中
        Intent intent = new Intent();
        if (viewModel.mMoveBaens.size() != 0) {
            viewModel.mMoveBaens.add(0,remove);
        }
        if (TOTAL_NUM - countAlready == 1) {
            viewModel.mMoveBaens.add(0,remove);
        }
        intent.putExtra("currently", viewModel.mMoveBaens);
//        Log.e("TAG", "onActivityResult: "+viewModel.mMoveBaens.size()  + "  "+viewModel.mMoveBaens.toString() );
        setResult(Contants.REQUEST_BACK_CODE, intent);
        super.onBackPressed();
    }

    //设置缓存柜成功
    @Override
    public void scanSuccess(String KFWZMC) {
        isSetCache = true;
        binding.tvScanGetScan.setText("缓存柜位置：" + KFWZMC);
        binding.btDoorTakeProgressSureSuccess.setEnabled(true);
        binding.btDoorTakeProgressSureSuccess.setBackgroundColor(getResources().getColor(R.color.background_main));
    }

    //设置缓存柜失败
    @Override
    public void scanFail(String errMsg) {
        new MyToast(this).showinfo(errMsg);
        binding.tvScanGetScan.setText("请重新扫码，设置缓存柜");
        isGetAll = false;
//        binding.btDoorTakeProgressSureSuccess.setEnabled(true);
    }
    //更新整个单子成功
    @Override
    public void submitSuccess() {
        new MyToast(DoorTakeProgressActivity.this).showinfo("取药成功");
        startActivity(new Intent(DoorTakeProgressActivity.this, DoorTakeIndexActivity.class));
    }
    //更新整个单子失败
    @Override
    public void submitFail(String errMsg) {
        //单子更新异常    ??? 可以认为是
        failSubmit = CreateDialog.failSubmit(DoorTakeProgressActivity.this, "取药失败", "该取药单已有其他人取药完成，请重新确认", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DoorTakeProgressActivity.this, DoorTakeIndexActivity.class));
                finish();
            }
        });
    }
    //TODO:接收PDA扫码广播，准备跳转
    class ScanReceiverDoorTake extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()){
                case Contants.WOW_NEW_ADD:
                    String stringExtra = intent.getStringExtra(Contants.WOW_NEW_KEY);
                    //               new MyToast(DoorTakeProgressActivity.this).showinfo("扫到的是: "+stringExtra);
//                    Log.e("onReceive1: ", remove.toString());
                    if(binding.llScanGetEnd.getVisibility() == View.GONE){
                        if(stringExtra.length() == 20){
                            //监管码
                            if(presenter.confimYPJGBM(stringExtra.substring(0,7))){
                                Intent intent2 = new Intent(DoorTakeProgressActivity.this, DoorTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove",remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            }else{
                                mMDialog= CreateDialog.failDialog(DoorTakeProgressActivity.this);
                            }
                            break;
                        }  else if(stringExtra.length() == 7){
                            //库位码
                            if(presenter.confimKFWZMC(stringExtra)){
                                Intent intent2 = new Intent(DoorTakeProgressActivity.this, DoorTakeProgressDetailActivity.class);
                                intent2.putExtra("topRemove",remove);
                                startActivityForResult(intent2, Contants.REQUEST_CODE);
                            }else{
                                mMDialog= CreateDialog.failDialog(DoorTakeProgressActivity.this);
                            }
                            break;
                        }else{
                                //剩余的都去匹配 药品码
                                //扫码后进行对比，true跳转，false弹框提示
                                if(presenter.confimYPSPBM(stringExtra)){
                                    Intent intent2 = new Intent(DoorTakeProgressActivity.this, DoorTakeProgressDetailActivity.class);
                                    intent2.putExtra("topRemove",remove);
                                    startActivityForResult(intent2, Contants.REQUEST_CODE);
                                }else{
                                    mMDialog= CreateDialog.failDialog(DoorTakeProgressActivity.this);
                                }
                        }
                    } else if(binding.llScanGetEnd.getVisibility() == View.VISIBLE){
                        //缓存柜
                        if((stringExtra.length() == 3)){
                            Log.e("PPP", "我开始设置位置了: "+ stringExtra);
                            presenter.setPlace(stringExtra);
                        }else{
                            new MyToast(DoorTakeProgressActivity.this).showinfo("请确认扫描的缓存柜");
                        }
                        break;
                    }else {
                        mMDialog= CreateDialog.failDialog(DoorTakeProgressActivity.this);
                        break;
                    }
            }
        }
    }
}
